import pandas as pd
import requests
import json
from datetime import datetime

#添加 AIGC 提供的背景图到数据库
# 读取 Excel 文件并指定 sheet 页
excel_file_path = 'C:\Users\luowenjie\Desktop\古诗词背景图\古诗词背景图0123.xlsx'
sheet_name = 'Sheet1'  # 替换为你的 sheet 页名称

# 使用 pandas 读取 Excel 文件
df = pd.read_excel(excel_file_path, sheet_name=sheet_name)

# 假设 Excel 文件中包含 `third_content_id` 和 `file_url` 列
# 这里我们不需要 `file_url` 列，但你可以根据需要处理它
batch_size = 100
data_list = []
for idx, row in df.iterrows():
    dynasty = row['dynasty'] if pd.notna(row['dynasty']) else ""  # 朝代
    author = row['author'] if pd.notna(row['author']) else ""     # 作者
    title = row['title'] if pd.notna(row['title']) else ""        # 标题
    content = row['content']  # 内容
    md5_value = row['md5'] if pd.notna(row['md5']) else ""  # md5
    background_image = row['imgUrlDst'] if pd.notna(row['imgUrlDst']) else ""  # 背景图
    #print(f"朝代:{dynasty},作者:{author},标题:{title}")
    # 检查 background_image 是否为空
    data_item = {
        "dynasty": dynasty,
        "author": author,
        "title": title,
        #"content": content,
        "md5": md5_value,
        "backgroundImage": background_image
    }
    data_list.append(data_item)
    # 每50条数据发送一次请求
    if (idx + 1) % batch_size == 0 or (idx + 1) == len(df):
        print(f"序号{idx + 1},开始添加古诗词背景图批次,时间:{datetime.now()}")
        # 调用接口
        headers = {
            'Content-Type': 'application/json'
        }
        #本地
        #api_url = "http://localhost:8080/api/ancientPoetry/addPoetryImage/invoke"
        #正式
        api_url = "http://106.55.8.90:7001/api/ancientPoetry/addPoetryImage/invoke"
        response = requests.post(api_url, headers=headers, data=json.dumps(data_list))
        print(f"保存成功,完成时间{datetime.now()},批次大小: {len(data_list)}")

        # 清空列表为下一批数据做准备
        data_list = []